package cn.medemede.servlet.action;

import cn.medemede.dao.UserpwdDao;
import cn.medemede.dao.UsersDao;
import cn.medemede.model.UserpwdBean;
import cn.medemede.model.UsersBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class Do_change implements Action{
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        UserpwdBean myUser=new UserpwdBean();
        UserpwdBean myUserOld=new UserpwdBean();
        UsersBean myUserInfo=new UsersBean();
        String forward="change_failed";
        String Register_name=request.getParameter("username");
        String Register_password=request.getParameter("new_password");
        String old_password=request.getParameter("old_password");
        String zname=request.getParameter("zname");
        String sex=request.getParameter("sex");
        String borth=request.getParameter("borth");
        String phone=request.getParameter("phone");
        String zposition=request.getParameter("province")+" "+request.getParameter("city");
        String email=request.getParameter("email");
        String[] favorite=request.getParameterValues("favorite");
        String favorite_s= "";
        if(favorite!=null)
            for (String s:favorite) {
                favorite_s=favorite_s+s+" ";
            }

        myUser.setUsername(Register_name);
        myUser.setPassword(Register_password);

        myUserOld.setUsername(Register_name);
        myUserOld.setPassword(old_password);

        myUserInfo.setUsername(Register_name);
        myUserInfo.setZname(zname);
        myUserInfo.setSex(sex);
        myUserInfo.setBorth(borth);
        myUserInfo.setPhone(phone);
        myUserInfo.setZposition(zposition);
        myUserInfo.setEmail(email);
        myUserInfo.setFavorite(favorite_s);

        if(UserpwdDao.find(myUserOld)){
        if(UserpwdDao.update(myUser)&& UsersDao.update(myUserInfo)){
            out.println("修改成功！");
            forward="change_suc";
        }else {
            out.println("修改失败！");
            forward="change_failed";
        }
        }else {
            out.println("修改失败！---密码错误或用户不存在!");
            forward="change_failed";
        }

        return forward;
    }
}
